import { missionManager } from "./MissionManager";
import { gameEventBus } from "../GameEventBus";

export enum MissionStatus {

    // 不可接的任务
    UNACCEPTABLE = 0,

    // 可接的任务
    ACCEPTABLE = 1,

    // 进行中的任务
    DURING = 2,

    // 可以提交的任务
    CANSUBMIT = 3,

    //失败的任务
    FAILED = 4,

    // 已完成
    FINISHED = 10,
}

export class Mission {

    id: number;

    name: string;

    toItem: string;

    status: number = MissionStatus.UNACCEPTABLE

    conditionType: string = "none";

    conditionTotal: number = 0;

    conditionCurrent: number = 0;

    conditionItemIds: string[] = [];

    preMission: number = 0;

    updateAcceptable() {
        if (this.status !== MissionStatus.UNACCEPTABLE) {
            return;
        }
        if (this.preMission) {
            const preMission = missionManager.getMissionById(this.preMission);
            if (preMission.status === MissionStatus.FINISHED) {
                this.status = MissionStatus.ACCEPTABLE
            }
        }
        else {
            this.status = MissionStatus.ACCEPTABLE
        }
    }

    accept() {
        if (this.status !== MissionStatus.ACCEPTABLE) {
            console.log("前置任务未完成！无法接受该任务！");
        }
        this.status = MissionStatus.DURING;

        if (this.conditionType === 'getClue') {
            gameEventBus.addListener("get", (data) => {     //调用gameEventBus.dispatch("方法","item")；
                for (let conditionItemId of this.conditionItemIds) {
                    if (conditionItemId === data) {
                        this.conditionCurrent++;
                        console.log("任务进度：",this.conditionCurrent, '/', this.conditionTotal)
                        if (this.conditionCurrent >= this.conditionTotal) {
                            this.status = MissionStatus.CANSUBMIT;
                        }
                    }
                }

            })
        }
        if (this.conditionType === 'useItem') {
            gameEventBus.addListener("use", (data) => {     //调用gameEventBus.dispatch("方法","item")；
                for (let conditionItemId of this.conditionItemIds) {
                    if (conditionItemId === data) {
                        this.conditionCurrent++;
                        console.log("任务进度：",this.conditionCurrent, '/', this.conditionTotal)
                        if (this.conditionCurrent >= this.conditionTotal) {
                            this.status = MissionStatus.CANSUBMIT;
                        }
                    }
                }

            })
        }
        

        if (this.conditionCurrent >= this.conditionTotal) {
            this.status = MissionStatus.CANSUBMIT;
        }
    }



    submit() {
        if (this.status !== MissionStatus.CANSUBMIT) {
            console.log("任务还没完成，不可提交！");
        }
        this.status = MissionStatus.FINISHED;
        missionManager.updateAcceptable();
    }
}